<?php
require("config.php");
require("db_mysql.inc");
require("functions.php");
$db = new ps_DB;

// If isNewEntry is true, user is adding a new safety rating
$isNewEntry = "false";
if( $_POST['isNewEntry'] == "true" )
	$isNewEntry = "true";

$rating = $_POST['safetyRating'];
$comment = $_POST['safetyComment'];
$markerLocationLat = $_POST['markerLocationLat'];
$markerLocationLng = $_POST['markerLocationLng'];
$zoom = $_POST['zoom'];
$userLocationLat = $_POST['userLocationLat'];
$userLocationLng = $_POST['userLocationLng'];
$isUserLocationKnown = $_POST['isUserLocationKnown'];

//	Clear POST entries, so that page refresh won't cause a problem.
// Doesn't work.
$_POST['safetyRating'] = "";
$_POST['safetyComment'] = "";
$_POST['markerLocationLat'] = "";
$_POST['markerLocationLng'] = "";
$_POST['zoom'] = "";
$_POST['isNewEntry'] = "";
$_POST['userLocationLat'] = "";
$_POST['userLocationLng'] = "";
$_POST['isUserLocationKnown'] = "";

//	Add marker data to db
//if($isNewEntry == "true" )
//	createMarker($markerLocationLat, $markerLocationLng, $comment, $rating, $db);

?>


<!DOCTYPE html>
<html>
<head>
	<title> Am I Safe Here? </title>
	<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
	<style type="text/css">
		html { height: 100% }
		body { height: 100%; margin: 0px; padding: 0px }
		#map_canvas { height: 100% }
	 </style>
	<script type="text/javascript"  src="http://maps.google.com/maps/api/js?sensor=true"></script>

	<script type="text/javascript">

	/*
	 *	Set initial parameters and then initialize map.
	 *	Set userLocation to user's current location if available, else use a default value.
	 *	initialLocation is same as userLocation, except when refreshing page after adding a marker. 
	 *	In this case, initialLocation is from previous page's state.
	 *	If this is a page reload from adding a pin, use parameters from previous session.
	 *	Pass in isUserLocationKnown to add / not add pin for user location.
	 */
	function initialize()
	{
		//	If its a new marker entry, set parameters to what user had before refresh
		<?php
		if( $isNewEntry == "true" )
		{
			echo 'var initialLocation = new google.maps.LatLng('.$markerLocationLat.','.$markerLocationLng.');';
			echo 'var initialZoom = '.$zoom.';';
			echo 'var userLocation = new google.maps.LatLng('.$userLocationLat.','.$userLocationLng.');';
			echo 'var isUserLocationKnown = '.$isUserLocationKnown.';';
			echo 'initializeMap(initialZoom, initialLocation, isUserLocationKnown, userLocation	);';
		}
		else
		{
		?>

			//	Set default position to Melbourne
			var initialLocation = new google.maps.LatLng(-37.80246476053294, 144.96681494140626);
			var userLocation = initialLocation;
			var initialZoom = 13;
	
			//	If geolocation is available and gets current position, use it.
			if(navigator.geolocation) 
			{
				navigator.geolocation.getCurrentPosition(function(position) 
					{
							userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
							initialLocation = userLocation;
							initializeMap(initialZoom, initialLocation, "true", userLocation);
					}, function() {
							initializeMap(initialZoom, initialLocation, "false", userLocation);
					}
				);
			}
			else
				initializeMap(initialZoom, initialLocation, "false", userLocation);
		<?php
		}
		?>
	}


	/*
	 *	Create map with given initial parameters.
	 *	Put all the markers on the map and add listeners for them.
	 *	Add a listener to check if user wants to mark a location.
	 *	Add a marker for user's current location, if available.
	 *	Also show startup window if necessary.
	 */
 	function initializeMap(zoom, initialLocation, isUserLocationKnown, userLocation)
 	{
		var myOptions = {
			zoom: zoom,
			center: initialLocation,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

		//	Put in all the markers for the places that have been marked so far
		populateMarkers(map);

		//	Add listener for when user wants to mark a position as unsafe
		google.maps.event.addListener(map, 'dblclick', function(event) {placeNewMarker(map, event.latLng, isUserLocationKnown, userLocation);} );

		// 	Add marker to show user where user is
		alert("isUserLocation : " + isUserLocationKnown);
		if( isUserLocationKnown == "true" )
	 	{
	 		alert(isUserLocationKnown); // not working!!!
			markerUserLocation = new google.maps.Marker( {position: userLocation, title:"You are here", map: map, icon: "http://maps.google.com/mapfiles/ms/micons/blue-dot.png" } );
	 	}

		//	Add InfoWindow to show instructions, unless user just added an entry
		<?php 
		if( $isNewEntry == "false" )
			echo 'addInstructionsInfoWindow(map, userLocation);';
		?>
 	}


	/*
	 *	Get all the markers for whole map.
	 *	Put the markers on the map.
	 *	Add listeners for each marker, to show details for the marker on click.
	 *	TODO: Later on only get markers for the area currently shown in the map.
	 *	TODO: Also have form to add user info on each marker.
	 */
	function populateMarkers(map)
	{
		<?php 
		$allLocations = getMarkersInZone(1, 1, $db); 	//	add end points of map instead of getting all info.

		echo 'var markers = new Array();';
		echo 'var infoWindows = new Array();';

		for( $i = 0; $i < count($allLocations); $i = $i + 2 )
		{
			$index = $i / 2;
			$currLat = $allLocations[$i];
			$currLng = $allLocations[$i+1];

			echo 'var location = new google.maps.LatLng('.$currLat.', '.$currLng.');';
			echo 'markers['.$index.'] = new google.maps.Marker( {position: location, title:"Coordinates: '.$currLat.', '.$currLng.'", map: map } );';
			$markerDetails = getMarkerDetails($currLat, $currLng, $db);

			//	TODO: Replace with function
			echo 'var contentString = "SafetyRating: '.$markerDetails[4].'";';
			echo 'contentString = contentString + "<p> Comments: '.$markerDetails[2].'";';
	    	echo 'contentString = contentString + "<div><p> Current Location:  + '.$currLat.', '.$currLng.'</div>";';
//			echo 'contentString = contentString + "<div id = ""> Add your safety rating and comment to this location. </div>";';

			echo 'infoWindows['.$index.'] = new google.maps.InfoWindow( {content: contentString, maxWidth: 800} );';
			echo 'google.maps.event.addListener( markers['.$index.'], "click", function() { infoWindows['.$index.'].open(map, markers['.$index.']); } );';

		}
		?>
	}


	/*
	 *	When user double clicks a location, add a marker instead of zooming in further.
	 *	Should only work when user is sufficiently zoomed in. 
	 *	Otherwise, just zoom in as normal.
	 *	After adding marker, open the safety warning form.
	 *	Add a onClick() listener for the marker.
	 * Needs userLocation and isUserLocationKnown to save state on page refresh.
	 */
	function placeNewMarker(map, markerLocation, isUserLocationKnown, userLocation) 
	{
		if( map.getZoom() < 14 )
			return;

		titleString = "Coordinates: " + markerLocation;
		var newMarker = new google.maps.Marker( {position: markerLocation, title:titleString, map: map} );

		var contentString = "<div><b>Current Location: </b> " + markerLocation + "</div>";
		contentString = contentString + getInputForm(map.getZoom(), markerLocation, isUserLocationKnown, userLocation);

		var infowindow = new google.maps.InfoWindow( {content: contentString, maxWidth: 800} );
		infowindow.open(map, newMarker);

//		clearListeners(map, 'dblclick'); 		//	doesn't work
		google.maps.event.addListener( newMarker, 'click', function() { infowindow.open(map, newMarker); } );
		//	TODO: Using hack below to prevent zooming on double click. Find a better way to disable zooming on double click when adding a marker.
		google.maps.event.addListener( marker, 'click', function() { infowindow.open(map, marker); } );		
	}


	/*
	 *	Create and add an instructions window to the map at given position.
	 */
	function addInstructionsInfoWindow(map, userLocation)
	{
		var infoWindowInstructions = new google.maps.InfoWindow();
		var contentStringInstructions = "<br />  Welcome to <b> Am I Safe Here?</b>, the crowdsourced safety warnings map!" +
		"<p> " +
		" Click on markers on the map to see the safety warnings around you. " +
		" <p>To warn other people of safety issues at a place, zoom into the area and double click it! " +
		"<p> <a href = 'info.php' target='_blank'>About us </a>";
		infoWindowInstructions.setContent(contentStringInstructions);
		infoWindowInstructions.setPosition(userLocation);
		infoWindowInstructions.open(map);
	}


	/*
	 *	Make the html input form for a marker and return it as a string.
	 *	Needs parameters to save state on page refresh.
	 */
	function getInputForm(zoom, markerLocation, isUserLocationKnown, userLocation)
	{
		var formContent = '<div><form name="newMarkerForm" method = "post" action = "home.php">' +
			'<input type="hidden" name="isNewEntry" value="true">' +
			'<input type="hidden" name="markerLocationLat" value=' + markerLocation.lat() + '>' +
			'<input type="hidden" name="markerLocationLng" value=' + markerLocation.lng() + '>' +
			'<input type="hidden" name="zoom" value=' + zoom + '>' +
			'<input type="hidden" name="isUserLocationKnown" value=' + isUserLocationKnown + '>' +
			'<input type="hidden" name="userLocationLat" value=' + userLocation.lat() + '>' +
			'<input type="hidden" name="userLocationLng" value=' + userLocation.lng() + '>' +
			'<br />Please rate the safety of this location (from 1-5, 5 being the safest): <br /> '+
			'<input type="radio" name="safetyRating" value="1" > 1 ' +
			'<input type="radio" name="safetyRating" value="2" > 2 ' +
			'<input type="radio" name="safetyRating" value="3" checked> 3 ' +
			'<input type="radio" name="safetyRating" value="4" > 4 ' +
			'<input type="radio" name="safetyRating" value="5" > 5 ' +
			'<br /><br />Add a note about the safety issues at this location: <br />' +
			'<textarea rows="3" cols = "40" name="safetyComment"></textarea>' +
			'<br /><br /> <input type="submit" value="Submit" />' +
			'</form></div>';
		return formContent;
	}

	</script>
</head>

<body onload="initialize()">
	<div id="map_canvas"></div>
</body>

</html>
